package o2o.web.actions.postman;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import map.AMapUtils;
import o2o.business.sms.JYSmsSeverBusiness;
import o2o.business.sms.data.SMS_TYPE;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.PostmanAgentRelationMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostmanSignCompanyMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.postman.PostmanOrderMemoryMan;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanOnlineMemory;
import o2o.cache.postman.PostmanPositionMemory;
import o2o.cache.postman.PostmanShopRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.tip.TipInfoPaotuiMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.PostmanAgentRelation;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.PostmanSignCompanyInfo;
import o2o.dao.PO.company.postman.SIGN_COMPANY_STATUS;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.ORDER_TYPE;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.postman.*;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.tip.TipInfoPaotui;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.dao.VO.postman.CityPostmanVerifyVO;
import o2o.postman.model.CityPostman;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.CommonUtils;
import o2o.web.actions.company.SysCityCompanyMan;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//配送员管理 (管理总后台)
@Controller
public class PostmanManagerController {

    //-------------------------------------------管理后台
    //配送员列表（按城市）---管理后台用
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/list")
    @ResponseBody
    public String city_postman_list(String token,
                                    String city, String province, String county,
                                    Integer isLock,//是否已停用  0未锁定  1锁定  2全部
                                    Integer isVerify,//-1或null全部   0未认证 1已认证 2认证中
                                    Long shopId,   // 是否是店铺获取配送员
                                    Integer type,   // 配送员类型  POSTMAN_TYPE // 1配送员  2工人  3提货点  4货运司机   6二级骑手
                                    String username,
                                    Long agentId,//商圈id
                                    Long carTipId,      //  车型
                                    Integer getNextLevel,// 是否获取下一级的代理
                                    Integer isCityAgent,  //是否按代理获取 0否 1是
                                    Long startTime, Long endTime,
                                    Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }
        if (getNextLevel == null) {
            getNextLevel = 0;
        }
        Long totalCount = 0l;
        List<CityPostman> reList = null;
        Map<String, Set<Long>> carTipIdMap = new HashMap<>();
        //业务员
        if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
            //属于改业务员的配送员 //只获取自己所管辖的
            StringBuffer sb = new StringBuffer();
            sb.append(" from ");
            sb.append(PojoTables.CityPostman);
            sb.append(" where delFlag =0 and isVerify = 1 and businessUsername = '").append(user.getUsername()).append("'");
            if (ValidateUtil.isNotNull(username)) {
                sb.append(" and username like '%").append(username).append("%'");
            }
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and createTime >= ").append(startTime).append(" and createTime <= ").append(endTime);
            }
            if (null != type && type != 0) {
                sb.append(" and type=").append(type).append(" ");
            }
            try {
                //数量
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());

                //数据
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select * ").append(sb.toString());
                sbSql.append(" order by isWork,verifyTime desc ");
                sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
                reList = (List<CityPostman>) UserDaoSql.getInstance().list(CityPostman.class, sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            if (ValidateUtil.isNotNull(city)) {
                if (User.notHasCityAuth(user.getUsername(), city, user.getUserType()) && !User.hasAdminAuth(user.getUserType())) {
                    return AjaxResult.errorResult("您没有访问该城市数据的权限");
                }
            }

            if (null == isLock) {
                isLock = 2;//0未锁定  1锁定  2全部
            }
            if (null != isVerify && 0 == -1 - isVerify) {
                isVerify = null;
            }
            if (!ValidateUtil.isAbsLong(shopId)) {
                shopId = null;
            }
            if (!ValidateUtil.isAbsInteger(type)) {
                type = null;
            }

            List<CityPostman> list = null;
//            // 根据城代获取所管理的商圈下的配送（代理可以管理多个商圈）
//            if (null != isCityAgent && isCityAgent - 1 == 0) {
//                list = listOfAgent(user.getUsername(), isLock);
//            } else {
//                list = CityPostmanMemory.getInstance().listOfCity(city, isLock, isVerify, username, startTime, endTime, shopId, type);
//            }

            //按商圈获取
            if (ValidateUtil.isAbsLong(agentId)) {
                List<String> tmpList = PostmanAgentRelationMemory.getInstance().listOfAgentId(agentId);
                if (ValidateUtil.isAbsList(tmpList)) {
                    list = new ArrayList<>();
                    for (int j = 0; j < tmpList.size(); j++) {
                        if (ValidateUtil.isNull(tmpList.get(j))) {
                            continue;
                        }
                        //根据账号获取所有配送信息,存入，返回
                        CityPostman postman = CityPostmanMemory.getInstance().getPostman(tmpList.get(j));
                        if (null == postman) {
                            continue;
                        }
                        if (isLock - 2 != 0) {   // 0启用 1停用 2 全部
                            if (isLock - postman.getIsLock() != 0) {
                                continue;
                            }
                        }
                        //是否已认证
                        if (null != isVerify) {
                            if (null == postman.getIsVerify() || 0 != isVerify - postman.getIsVerify()) {
                                continue;
                            }
                        } else {
                            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                                    && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
                                continue;
                            }
                        }
                        if (ValidateUtil.isNotNull(username) && !SysCommon.hasKeyword(postman.getUsername(), username)) {
                            continue;
                        }
                        list.add(postman);
                    }
                }
            } else {
                // 根据城代获取所管理的商圈下的配送（代理可以管理多个商圈）
                if (null != isCityAgent && isCityAgent - 1 == 0) {
                    list = PostmanMan.listOfAgent(user.getUsername(), isLock);
                    if (null != list && ValidateUtil.isAbsList(list) && null != type && type != 0) {
                        final int tempType = type;
                        list = list.stream().filter(l -> tempType == l.getType()).collect(Collectors.toList());
                    }
                } else {
                    if (ValidateUtil.isNotNull(city)) {
                        if (null != isVerify) {
                            list = CityPostmanMemory.getInstance().listOfCity(city, isLock, isVerify, username, startTime, endTime, shopId, type);
                        } else {
                            list = CityPostmanMemory.getInstance().listOfCity(city, isLock, username, startTime, endTime, shopId, type);
                        }
                    } else {
                        list = getCityPostmanAll(isLock, username, startTime, endTime, type, page, size);
                    }
                }
            }
            if (ValidateUtil.isAbsList(list)) {
                Stream<CityPostman> stream = list.stream().map(b -> {
                    PostmanMan.postmanHasCarTip(b.getUsername(), carTipIdMap);
                    return b;
                });
                if (carTipId != null) {
                    stream = stream.filter(b -> {
                        Set<Long> carSetId = carTipIdMap.get(b.getUsername());
                        if (carSetId == null || !carSetId.contains(carTipId)) {
                            return false;
                        }
                        return true;
                    });
                }
                list = stream.collect(Collectors.toList());
            }
            if (ValidateUtil.isAbsList(list)) {
                JYListSort.sortDesc(list, "isWork", "verifyTime");
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                if (null != pageList && null != pageList.list && ValidateUtil.isAbsList(pageList.list)) {
                    reList = (List<CityPostman>) pageList.list;
                    totalCount = Long.parseLong(pageList.totalCount + "");
                }
            }
        }

        if (ValidateUtil.isAbsList(reList)) {
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < reList.size(); i++) {
                if (null == reList.get(i)) {
                    continue;
                }
                CityPostman cityPostman = reList.get(i);
                if (null == cityPostman) {
                    continue;
                }
                CityPostmanVO vo = addOne(cityPostman);
                if (null == vo) {
                    continue;
                }
                if (getNextLevel != 1 && ValidateUtil.isNotNull(county) && !cityPostman.getCounty().equals(county)) {
                    continue;
                }
                Long postmanAgentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(vo.getUsername());
                if (postmanAgentId != null) {
                    vo.setAgentId(postmanAgentId);
                }
                vo.setLastOnlineTime(PostmanOnlineMemory.getInstance().get(cityPostman.getUsername()));
                dealCarTipNames(vo, carTipIdMap);
                voList.add(vo);
            }
            return AjaxResult.successResult(totalCount, voList.size(), voList);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // todo  一乙处理车型问题
    public void dealCarTipNames(CityPostmanVO vo, Map<String, Set<Long>> carTipIdMap) {
        if (vo == null || carTipIdMap == null) {
            return;
        }
        Set<Long> carTipIdSet = carTipIdMap.get(vo.getUsername());
        if (carTipIdSet != null && !carTipIdSet.isEmpty()) {
            Set<String> temp = new HashSet<>();
            for (Long id : carTipIdSet) {
                TipInfoPaotui infoPaotui = TipInfoPaotuiMemory.getInstance().getById(id);
                if (infoPaotui != null) {
                    temp.add(infoPaotui.getName());
                }
            }
            vo.setCarTipNames(StringUtils.join(temp, ","));
        }
    }


    public List<CityPostman> getCityPostmanAll(Integer isLock, String username, Long startTime, Long endTime, Integer type, Integer page, Integer size) {
        String sql = "SELECT * FROM " + PojoTables.CityPostman +
                " WHERE delflag = 0 AND isVerify = 1 " +
                (startTime != null && endTime != null ? (" AND createTime Between " + startTime + " AND " + endTime) : "") +
                (isLock != null && isLock != 2 ? (" AND isLock = " + isLock) : "") +
                (StringUtils.isNotEmpty(username) ? (" AND username = " + username) : "") +
                (type != null ? (" AND type = " + type) : "") +
                " ORDER BY createTime desc ";
        List<CityPostman> list = null;
        try {
            list = (List<CityPostman>) UserDaoSql.getInstance().list(CityPostman.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }


//    //新平台配送员新增(基于不带商圈)
//    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/new/add2")
//    @ResponseBody
//    public String city_postman_new_add2(String username,String city,String province,String county,
//                                       String name,String signature,String telPhone,
//                                       String phone2,String sex,String address,Long shopId) {
//        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
//        Integer type = 1;
//        if (ValidateUtil.isNull(city)) {
//            return AjaxResult.errorResult("市不能为空");
//        }
//
//        if (ValidateUtil.isNull(shopId)) {
//            return AjaxResult.errorResult("门店不能为空");
//        }
//
//        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
//            return AjaxResult.errorResult("您没有访问该城市数据的权限");
//        }
//
//        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
//            return AjaxResult.errorResult("您没有修改该城市店铺的权限");
//        }
//
//        //检测用户是否已经存在
//        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
//        if (null == userInfo) {//系统中无该用户
//            //新建管理员
//            UserInfo u = new UserInfo(UserType.POSTMAN, username, name, signature, telPhone, phone2, sex,
//                    province, city, county, address, user.getUsername());
//            try {
//                String psw = "123456";
//                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
//                    psw = username.substring(5, 11);
//                }
//                ResultInfo resultInfo = User.addUser(u, psw);
//                if (!resultInfo.isSuccess()) {
//                    return AjaxResult.errorResult(resultInfo.getError());
//                }
//            } catch (Exception e) {
//                return AjaxResult.errorResult("新增失败，请稍后再试");
//            }
//
//        } else {//修改为配送员
//            if (0 != UserType.POSTMAN - userInfo.getUserType()) {
//                User.modifyUserType(username, UserType.POSTMAN);
//            }
//        }
//
//        //添加对应的权限
//        Long time = DateUtils.getCurrTime();
//        CityPostman cityPostman = new CityPostman(username, province, city, county, null, "", user.getUsername(), time);
//        cityPostman.setPostman_name(user.getUsername());
//        if (ValidateUtil.isNotAbsInteger(type)) {
//            type = 1;
//        }
//        //TODO ShopId没作用
////        if (ValidateUtil.isAbsLong(shopId)) {
////            cityPostman.setShopId(shopId);
////        }
//        cityPostman.setType(type);
//        Connection conn = null;
//        try {
//            conn = UserDaoSql.getInstance().getConnection();
//            conn.setAutoCommit(false);
//        } catch (Exception e) {
//            e.printStackTrace();
//            UserDaoSql.getInstance().rollback(conn);
//            UserDaoSql.getInstance().close(conn);
//        }
//        Long postmanId = null;
//        if (SYS_SETTINGS.POSTMAN_MUST_VERIFY != null && SYS_SETTINGS.POSTMAN_MUST_VERIFY == 1) {
//            if (SYS_SETTINGS.MANAGER_POSTMAN_NEED_VERIFY == 1) {
//
//            } else {
//                cityPostman.setIsVerify(1);
//            }
//        } else {
//            cityPostman.setIsVerify(1);
//        }
//        try {
//            postmanId = UserDaoSql.getInstance().saveObj(PojoTables.CityPostman, cityPostman, conn);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            UserDaoSql.getInstance().rollback(conn);
//            UserDaoSql.getInstance().close(conn);
//            return AjaxResult.errorResult("添加失败，请稍后再试");
//        }
//
//        //TODO 新增骑手时绑定店铺
//        //==============================================
//        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
//
//        PostmanShopRelation p = setPostmanShopRelation(shopInfo, cityPostman, user.getUsername());
//        try {
//            UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_SHOP_RELATION, p, conn);
//        } catch (Exception e) {
//            e.printStackTrace();
//            UserDaoSql.getInstance().rollback(conn);        // 回滚
//            UserDaoSql.getInstance().close(conn);
//            return AjaxResult.errorResult("操作失败，请稍后重试");
//        }
//        //===============================================
//
//        try {
//            conn.commit();
//        } catch (Exception e) {
//            e.printStackTrace();
//            UserDaoSql.getInstance().rollback(conn);
//            return AjaxResult.errorResult("添加失败");
//        } finally {
//            UserDaoSql.getInstance().close(conn);
//        }
//
//        // 关联表缓存
//        PostmanShopRelationMemory.getInstance().run();
//
//        //缓存中新增
//        CityPostmanMemory.getInstance().add(time);
//        try {
//            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_ADD).setLong01(time);
//            JmsSender.setTopicSender(notify);
//        } catch (Exception e) {
//        }
//
////        TODO 商圈-消息队列
////        if (ValidateUtil.isID(postmanId)) {
////            PostmanAgentRelationMemory.getInstance().add(agentId);
////            // 数据同步
////            try {
////                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD).setLong01(agentId);
////                JmsSender.setTopicSender(notify);
////            } catch (Exception e) {
////            }
////
//        return AjaxResult.successResult();
//    }


    //新增配送员（不带商圈）
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/add")
    @ResponseBody
    public String city_postman_add(String token, String username, String city, String province, String county, String region,
                                   Long shopId,
                                   Long agentId,
                                   Integer type, // 配送员类型1 正常配送员 2.工人
                                   String name, String signature, String telPhone, String phone2, String sex, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有修改该城市店铺的权限");
        }

        //检测用户是否已经存在
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {//系统中无该用户
            //新建管理员
            UserInfo u = new UserInfo(UserType.POSTMAN, username, name, signature, telPhone, phone2, sex,
                    province, city, county, address, user.getUsername());
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = username.substring(5, 11);
                }
                ResultInfo resultInfo = User.addUser(u, psw);
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }

        } else {//修改为配送员
            if (0 != UserType.POSTMAN - userInfo.getUserType()) {
                User.modifyUserType(username, UserType.POSTMAN);
            }
        }

        //添加对应的权限
        Long time = DateUtils.getCurrTime();
        CityPostman cityPostman = new CityPostman(username, province, city, county, region, "", user.getUsername(), time);

        if (ValidateUtil.isNotAbsInteger(type)) {
            type = 1;
        }
        if (ValidateUtil.isAbsLong(shopId)) {
            cityPostman.setShopId(shopId);
        }
        cityPostman.setType(type);
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
        }
        Long postmanId = null;
        if (SYS_SETTINGS.POSTMAN_MUST_VERIFY != null && SYS_SETTINGS.POSTMAN_MUST_VERIFY == 1) {
            if (SYS_SETTINGS.MANAGER_POSTMAN_NEED_VERIFY == 1) {

            } else {
                cityPostman.setIsVerify(1);
            }
        } else {
            cityPostman.setIsVerify(1);
        }
        try {
            postmanId = UserDaoSql.getInstance().saveObj(PojoTables.CityPostman, cityPostman, conn);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("添加失败，请稍后再试");
        }

        if (ValidateUtil.isID(agentId)) {
            // 啥商圈信息
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
            if (cityAgent == null) {
                return AjaxResult.errorResult("商圈信息不存在");
            }
            //添加代理对应的配送员关系
            PostmanAgentRelation relation = new PostmanAgentRelation();
            relation.setAgentId(agentId);
            relation.setAgentUsername(cityAgent.getUsername());
            relation.setPostmanUsername(username);
            relation.setPostmanId(postmanId);
            relation.setCreateTime(time);
            relation.setDelFlag(0);
            relation.setProvince(province);
            relation.setCity(city);
            relation.setCounty(county);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.POSTMAN_AGENT_RELATION, relation);
            } catch (SQLException e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
                return AjaxResult.errorResult("条件代理关系时失败，请稍后再试");
            }
        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            return AjaxResult.errorResult("添加失败");
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        //缓存中新增
        CityPostmanMemory.getInstance().add(time);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_ADD).setLong01(time);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        if (ValidateUtil.isID(postmanId)) {
            PostmanAgentRelationMemory.getInstance().add(agentId);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD).setLong01(agentId);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }

        }
        return AjaxResult.successResult();
    }

    //新增配送员（好管家店铺）
    @RequestMapping(method = RequestMethod.POST, value = "/shop/postman/add")
    @ResponseBody
    public String shop_postman_add(String token, String username, String city, String province, String county, String region,
                                   Long shopId, Integer type, // 配送员类型1 正常配送员 2.工人
                                   String name, String signature, String telPhone, String phone2, String sex, String address) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.errorResult("您不是店主");
        }
        // ；检测店铺商信息
        Long agentByShopId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopInfo.getId());
        if (!ValidateUtil.isAbsLong(agentByShopId)) {
            return AjaxResult.errorResult("请核实店铺信息");
        }
        // 账号
        if (ValidateUtil.isNotMobile(username)) {
            return AjaxResult.errorResult("账户格式不正确");
        }
        // 名为空时，用账户代替
        if (ValidateUtil.isNull(name)) {
            name = username;
        }

        // 啥商圈信息
        CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentByShopId);
        if (cityAgent == null) {
            return AjaxResult.errorResult("商圈信息不存在");
        }
        if (ValidateUtil.isNotAbsInteger(type)) {
            type = 2; // 默认是工人
        }
        //检测用户是否已经存在
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) { //系统中无该用户
            //新建管理员
            UserInfo u = new UserInfo(UserType.POSTMAN, username, name, signature, telPhone, phone2, sex,
                    shopInfo.getProvince(), shopInfo.getCity(), shopInfo.getCounty(), address, user.getUsername());
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = username.substring(5, 11);
                }
                ResultInfo resultInfo = User.addUser(u, psw);
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }

        } else { //修改为配送员
            if (0 != UserType.POSTMAN - userInfo.getUserType()) {
                User.modifyUserType(username, UserType.POSTMAN);
            } else {
                return AjaxResult.errorResult("系统中已有此配送员信息");
            }
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        Long time = DateUtils.getCurrTime();
        if (null == postman) {
            //添加对应的权限
            CityPostman cityPostman = new CityPostman(username, shopInfo.getProvince(), shopInfo.getCity(), shopInfo.getCounty(), region, "", user.getUsername(), time);
            cityPostman.setType(type);
            cityPostman.setShopId(shopInfo.getId());
            cityPostman.setIsLock(0);
            cityPostman.setIsVerify(1);

            //转成英文城市名称
            if (ValidateUtil.isNotNull(city)) {
                cityPostman.setCityEN(JYPinyinHelper.toHanyuPinyin(city));
            }

            try {
                UserDaoSql.getInstance().insertObj(PojoTables.CityPostman, cityPostman);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后再试");
            }
            //缓存中新增
            CityPostmanMemory.getInstance().add(time);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_ADD).setLong01(time);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
            postman = CityPostmanMemory.getInstance().getPostman(username);
        }

        // 添加代理问题
        Long agentByPostmanUsername = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(postman.getUsername());
        if (agentByPostmanUsername == null) {
            //添加代理对应的配送员关系
            PostmanAgentRelation relation = new PostmanAgentRelation();
            relation.setAgentId(cityAgent.getId());
            relation.setAgentUsername(cityAgent.getUsername());
            relation.setPostmanUsername(username);
            if (null != postman) {
                relation.setPostmanId(postman.getId());
            }
            relation.setCreateTime(time);
            relation.setDelFlag(0);
            relation.setProvince(shopInfo.getProvince());
            relation.setCity(shopInfo.getCity());
            relation.setCounty(shopInfo.getCounty());

            try {
                UserDaoSql.getInstance().insertObj(PojoTables.POSTMAN_AGENT_RELATION, relation);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("条件代理关系时失败，请稍后再试");
            }
            PostmanAgentRelationMemory.getInstance().add(cityAgent.getId());
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD).setLong01(cityAgent.getId());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        return AjaxResult.successResult();
    }

    //修改配送员
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/modify")
    @ResponseBody
    public String city_postman_modify(String token, CityPostmanVO info, Long agentId, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == info) {
            return AjaxResult.errorResult("输入信息有误，请查证");
        }

        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (User.notHasCityAuth(user.getUsername(), info.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("您没有修改该城市的权限");
        }


        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(info.getUsername());
        if (null == cityPostman) {
            return AjaxResult.errorResult("该配送员已不存在，请查证");
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(info.getUsername());
        if (null == userInfo) {
            return AjaxResult.errorResult("该配送员已不存在，请查证.");
        }

        if (null == info.getIsWork()) {
            info.setIsWork(cityPostman.getIsWork());
        }

//        //修改上班状态
//        if (0 == info.getIsWork() - cityPostman.getIsWork()) {
//            StringBuffer sb = new StringBuffer();
//            sb.append("update ").append(PojoTables.CityPostman).append(" set isWork = ").append(info.getIsWork()).append(",updateUser='").append(user.getUsername())
//                    .append("'");
//            if (ValidateUtil.isNotNull(info.getProvince())) {
//                sb.append(", province ='").append(info.getProvince()).append("'");
//            }
//            if (ValidateUtil.isNotNull(info.getCity())) {
//                sb.append(", city ='").append(info.getCity()).append("'");
//                if (ValidateUtil.isNotNull(info.getCounty())) {
//                    sb.append(", county ='").append(info.getCounty()).append("'");
//                } else {
//                    sb.append(", county =''");
//                }
//            }
//            sb.append(" where delFlag=0 and username='").append(info.getUsername()).append("' ");
//            try {
//                UserDaoSql.getInstance().executeBySql(sb.toString());
//            } catch (SQLException e) {
//                e.printStackTrace();
//                return AjaxResult.errorResult("修改工人的工作状态时出错，请稍后再试");
//            }
//
//            // CityPostmanMemory.getInstance().setIsWork(info.getUsername(), info.getIsWork());
//            CityPostmanMemory.getInstance().modifyByUsername(cityPostman.getUsername());
//            try {
//                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(info.getUsername());
//                JmsSender.setTopicSender(notify);
//            } catch (Exception e) {
//            }
//        }


        StringBuffer sb = new StringBuffer();
        boolean needUpdate = false;
        String isWork = "";
        //修改上班状态
        if (0 != info.getIsWork() - cityPostman.getIsWork()) {
            isWork = " isWork = " + info.getIsWork() + ",";
            needUpdate = true;
        }
        sb.append("update ").append(PojoTables.CityPostman).append(" set ").append(isWork).append(" updateUser='").append(user.getUsername()).append("'");
//        if (ValidateUtil.isNotNull(info.getProvince())) {
//            sb.append(", province ='").append(info.getProvince()).append("'");
//        }
//        if (ValidateUtil.isNotNull(info.getCity())) {
//            sb.append(", city ='").append(info.getCity()).append("'");
//            if (ValidateUtil.isNotNull(info.getCounty())) {
//                sb.append(", county ='").append(info.getCounty()).append("'");
//            } else {
//                sb.append(", county =''");
//            }
//        }


        if (ValidateUtil.isNotNull(info.getCity())) {
            needUpdate = true;
            sb.append(", province ='").append(info.getProvince()).append("'");
            sb.append(", city ='").append(info.getCity()).append("'");
            if (ValidateUtil.isNotNull(info.getCounty())) {
                sb.append(", county ='").append(info.getCounty()).append("'");
            } else {
                sb.append(", county =''");
            }
        }
        sb.append(" where delFlag=0 and username='").append(info.getUsername()).append("' ");
        if (needUpdate) {
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改工人的工作状态时出错，请稍后再试");
            }

            if (ValidateUtil.isNotNull(info.getCity())) {
                // 重新加载
                CityPostmanMemory.getInstance().reloadCity(info.getCity());
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(info.getCity());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            } else {
                CityPostmanMemory.getInstance().modifyByUsername(cityPostman.getUsername());
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(info.getUsername());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }

//            // CityPostmanMemory.getInstance().setIsWork(info.getUsername(), info.getIsWork());
//            CityPostmanMemory.getInstance().modifyByUsername(cityPostman.getUsername());
//            try {
//                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(info.getUsername());
//                JmsSender.setTopicSender(notify);
//            } catch (Exception e) {
//            }
        }

        if (ValidateUtil.isNotNull(info.getCity())) {
            String province = info.getProvince();
            if (ValidateUtil.isNull(province)) {
                province = "";
            }
            String city = info.getCity();
            if (ValidateUtil.isNull(city)) {
                city = "";
            }
            String county = info.getCounty();
            if (ValidateUtil.isNull(county)) {
                county = "";
            }
            // 修改用户信息
            StringBuffer sbU = new StringBuffer();
            sbU.append("update ").append(PojoTables.UserInfo).append(" set province='").append(province)
                    .append("',city='").append(city).append("',county='").append(county).append("',updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and username = '").append(info.getUsername()).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbU.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            UserInfoMemory.getInstance().modifyUserInfo(info.getUsername());
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_MODIFY).setStr01(info.getUsername());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }


        //保存图片
        if (null != fileUploadInfo && null != fileUploadInfo.getImage()) {
            //存储图片
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setSignPhoto(filePath);
        }
        //修改工人的信息
        User.modifyUserInfo(info.getUsername(), info.getName(), info.getSignPhoto(), info.getSex(), info.getTelPhone(), user.getUsername());

        CityPostmanVerify cityPostmanVerify = new CityPostmanVerify();
        cityPostmanVerify.setUsername(info.getUsername());
        cityPostmanVerify.setName(info.getName());
        cityPostmanVerify.setSex(info.getSex() == "男" ? 1 : 2);
        cityPostmanVerify.setTelephone(info.getTelPhone());
        try {
            PostmanMan.updatePostmanVerify(user, cityPostmanVerify, fileUploadInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        // 修改配送员的商圈信息
        if (ValidateUtil.isID(agentId)) {
            ResultInfo resultInfo = PostmanMan.dealPostmanAgentRelation(cityPostman, agentId + "");
            if (resultInfo == null) {
                return AjaxResult.errorResult("处理失败,请稍后重试");
            }
            if (resultInfo != null && !resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        }
        return AjaxResult.successResult();
    }


    //删除
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/delete")
    @ResponseBody
    public String city_postman_delete(String token, String username, String city, String province, String county
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }


        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }
        if (SYS_SETTINGS.HAS_ORDER_REFUSE_DEL_SHOP_POSTMAN != null && SYS_SETTINGS.HAS_ORDER_REFUSE_DEL_SHOP_POSTMAN == 1 && PostmanMan.postmanHasOrder(username)) {
            return AjaxResult.errorResult("当前骑手已存在订单");
        }

        String users = username.replace(",", "','");
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.CityPostman).append(" set delFlag = 1,updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and username in ('").append(users).append("')");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //  删除postman_verify表中的数据
        StringBuffer sb2 = new StringBuffer();
        sb2.append("update ").append(PojoTables.POSTMAN_VERITY).append(" set delFlag = 1").append(" where delFlag = 0 and username in ('").append(users).append("')");
        try {
            UserDaoSql.getInstance().executeBySql(sb2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除2失败，请稍后再试.");
        }

        // 修改用户类型为普通用户
//        User.modifyUserType(username, UserType.USER);
        //在缓存中删除
        CityPostmanMemory.getInstance().reloadCity(city);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 删除配送员与商圈的关系
        StringBuffer sb3 = new StringBuffer();
        sb3.append("update ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" set delFlag = 1").append(" where delFlag = 0 ")
                .append(" and postmanUsername ='").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb3.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除3失败，请稍后再试.");
        }
        Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(username);
        if (ValidateUtil.isID(agentId)) {
            PostmanAgentRelationMemory.getInstance().reloadByAgentId(agentId);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_RELOAD_BY_AGENT).setLong01(agentId);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }

        // 修改用户类型
        User.delRevertUserStr(username);

        return AjaxResult.successResult();
    }


    // 锁定解锁骑手
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/lock")
    @ResponseBody
    public String city_postman_Lock(String token, String sysAppKey, String username, String city, String province, String county, Integer isLock) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), city, user.getUserType())) {
            return AjaxResult.errorResult("您没有访问该城市数据的权限");
        }
        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }

        if (null == UserInfoMemory.getInstance().getUserInfo(username)) {
            return AjaxResult.errorResult("锁匠不存在");
        }
        if (null == CityPostmanMemory.getInstance().getPostman(username)) {
            return AjaxResult.errorResult("锁匠不存在.");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }
//        if (ValidateUtil.isAbsInteger(isLock) || ((isLock != 1) && (isLock != 0))) {
//            return AjaxResult.errorResult("请确认停用还是启用");
//        }

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.CityPostman).append(" set isLock = '").append(isLock).append("',updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and city = '")
                .append(city).append("' and username = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("停用/启用锁匠失败，请稍后再试");
        }

        StringBuilder sb2 = new StringBuilder();
        sb2.append("update ").append(PojoTables.UserInfo).append(" set isLock = '").append(isLock).append("',updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and username = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("停用/启用锁匠失败，请稍后再试。");
        }

        //在缓存中更新
        CityPostmanMemory.getInstance().setIsLock(username, isLock);
        UserInfoMemory.getInstance().modifyUserInfo(username);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_MODIFY).setStr01(username);//o2o.business.jms  MQDataBusiness
            JmsSender.setTopicSender(notify);
            JMSNotify notify2 = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_LOCK_SET).setStr01(username).setInt01(isLock);//o2o.business.jms  MQDataBusiness
            JmsSender.setTopicSender(notify2);
        } catch (Exception e) {
        }


        if (isLock == 1) {
            //发送短信
//            SMSInfo smsInfo = new SMSInfo(username, null,
//                    null, DUBBO_SMS_TYPE.OTHER,
//                    SYS_CONFIG_SMS.POSTMAN_LOCK);
//            SMSThreadMap.smsCodeSet.add(smsInfo);

            JYSmsSeverBusiness.sendSMS(sysAppKey, username, SMS_TYPE.POSTMAN_LOCK);
        }


        return AjaxResult.successResult();
    }

    //管理员修改配送员营业状态
    @RequestMapping(method = RequestMethod.POST, value = "/admin/postman/status/modify")
    @ResponseBody
    public String admin_postman_status_modify(String token, String username, Integer isWork) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == cityPostman) {
            return AjaxResult.errorResult("未查询到配送员信息");
        }


        if (null == isWork) {
            return AjaxResult.errorResult("是否上班不能为空");
        }
//        StringBuilder sb = new StringBuilder();
//        sb.append("update ").append(PojoTables.CityPostman).append(" set isWork = ").append(isWork).append(",updateUser = '")
//                .append(user.getUsername()).append("' where username = '").append(user.getUsername()).append("' and delFlag = 0");
//        try {
//            UserDaoSql.getInstance().executeBySql(sb.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("修改失败，请稍后再试");
//        }
//        CityPostmanMemory.getInstance().setIsWork(user.getUsername(), isWork);
        ResultInfo resultInfo = PostmanMan.cityPostmanStatusModify(username, isWork);
        if (null != resultInfo) {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        } else {
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        return AjaxResult.successResult();
    }


    // 一键上下班/锁定解锁（管理员）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/all/postman/status/modify")
    @ResponseBody
    public String all_postman_lock(String token, String city, Integer isLock, Integer isWork) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("城市不能为空");
        }

//        isLock 是否锁定（1是，0否）
//        isWork 是否工作（1是，0否）


        if (null == isWork && null == isLock) {
            return AjaxResult.errorResult("请先选择状态");
        }

        if (null != isLock && 1 == isLock) {
            // 全部锁定，直接锁定该城市的，并且设置为下班
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.CityPostman).append(" set isWork =0,isLock=1,updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("' ");  //1锁定，0正常
            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                sb.append(" and businessUsername='").append(user.getUsername()).append("'");
            }

            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后");
            }
        } else if (null != isLock && 0 == isLock) {
            // 一键解锁
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.CityPostman).append(" set isLock=0,updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("' and isLock = 1");  //1锁定，0正常
            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                sb.append(" and businessUsername='").append(user.getUsername()).append("'");
            }
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后");
            }
        } else if (null != isWork && 0 == isWork) {
            // 一键下班
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.CityPostman).append(" set isWork =0,updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("'");

            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                sb.append(" and businessUsername='").append(user.getUsername()).append("'");
            }
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后");
            }
        } else if (null != isWork && 1 == isWork) {
            // 一键上班
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.CityPostman).append(" set isWork =1,updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("' and isLock = 0 ");

            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                sb.append(" and businessUsername='").append(user.getUsername()).append("'");
            }
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后");
            }
        }
//
//        StringBuilder sb = new StringBuilder();
//
//        //  1 一键上下班(针对解锁的)
//        if (ValidateUtil.isAbsInteger(isWork)) {
//            sb.append("update ").append(PojoTables.CityPostman).append(" set isWork = ").append(isWork)
//                    .append(",updateUser = '").append(user.getUsername())
//                    .append("' where delFlag = 0").append(" and city = '").append(city).append("' and isLock = 0");  //1锁定，0正常
//        }
//
//        //1 一键锁定(下班状态)  2 一键解锁
//        if (ValidateUtil.isAbsInteger(isLock)) {
//            if (0 == isLock) { //isLock 解锁后---下班
//                isWork = 0;
//            }
//            if (1 == isLock) {
//                isWork = 0;
//            }
//            sb.append("update ").append(PojoTables.CityPostman).append(" set isLock = ").append(isLock)
//                    .append(",isWork = ").append(isWork)
//                    .append(",updateUser = '").append(user.getUsername())
//                    .append("' where delFlag = 0 and city = '").append(city).append("'")
//                    .append(isLock == 0 ? " and isLock=1" : " and isLock = 0");
////            isLock == 0 ? " and isLock=1" : " and isLock=" + 1
//        }
//
//        if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
//            sb.append(" and businessUsername='").append(user.getUsername()).append("'");
//        }
//        try {
//            UserDaoSql.getInstance().executeBySql(sb.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("修改失败，请稍后");
//        }

        //在缓存中更新
        CityPostmanMemory.getInstance().reloadCity(city);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    //--------------------------------商圈下的配送员管理
    //商圈下的配送员列表
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/list")
    @ResponseBody
    public String city_postman_list(String token, Long agentId,
                                    String province, String county, String region,
                                    Integer type,
                                    Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("商圈id不能为空");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        List<String> list = PostmanAgentRelationMemory.getInstance().listOfAgentId(agentId);
        //需要按类别查询吗
        if (ValidateUtil.isAbsInteger(type) && ValidateUtil.isAbsList(list)) {
            //需要
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String username = list.get(i);
                if (ValidateUtil.isNull(username)) {
                    continue;
                }

                //配送员的上班状态
                CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
                if (null == cityPostman) {
                    continue;
                }
                if (0 != cityPostman.getType() - type) {
                    continue;
                }

                //配送员的个人信息
                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
                if (null == userInfo) {
                    return null;
                }

                if (0 == 1 - cityPostman.getDelFlag()) {
                    continue;
                }
                CityPostmanVO cityPostmanVO = new CityPostmanVO();
                try {
                    ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null != cityPostman) {
                    cityPostmanVO.setIsWork(cityPostman.getIsWork());
                }

                cityPostmanVO.setType(cityPostman.getType());
                voList.add(cityPostmanVO);
            }
            if (ValidateUtil.isAbsList(voList)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
                if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                    return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
                }
            }

        } else {
            if (ValidateUtil.isAbsList(list)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                if (null != pageList && null != pageList.list && pageList.list.size() > 0) {

                    List<CityPostmanVO> voList = new ArrayList<>();
                    for (int i = 0; i < pageList.list.size(); i++) {
                        String username = (String) pageList.list.get(i);
                        if (ValidateUtil.isNull(username)) {
                            continue;
                        }

                        //配送员的个人信息
                        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
                        if (null == userInfo) {
//                            return null;
                            continue;
                        }
                        CityPostmanVO cityPostmanVO = new CityPostmanVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }


                        //配送员的上班状态
                        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
                        if (null != cityPostman) {
                            cityPostmanVO.setIsWork(cityPostman.getIsWork());
                        }
                        if (0 == 1 - cityPostman.getDelFlag()) {
                            continue;
                        }

                        cityPostmanVO.setType(cityPostman.getType());
                        voList.add(cityPostmanVO);
                    }


                    //返回数据
                    if (ValidateUtil.isAbsList(voList)) {
                        return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
                    }
                }
            }
        }


        return AjaxResult.successResult(0, 0, null);
    }


    //商圈下添加配送员
    //新增配送员（带商圈）
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/add")
    @ResponseBody
    public String city_postman_add(String token, Long agentId, String username, String city, String province, String county, String region,
                                   Integer type, // 配送员类型1 正常配送员 2.工人
                                   String name, String signature, String telPhone, String phone2, int sex, String address,
                                   Long carTipId,      // 车型id
                                   CityPostmanVerify info, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("代理ID不能为空");
        }
        CityAgent cAgent = CityAgentMemory.getInstance().getById(agentId);
        if (null == cAgent) {
            return AjaxResult.errorResult("您不是代理，无权新增");
        }
        //身份证名称 身份证号
        if (ValidateUtil.isNull(info.getOwner())) {
            info.setOwner(info.getName());
//            return AjaxResult.errorResult("请填写姓名");
        }
//        if (ValidateUtil.isNull(info.getOwnerID())) {
//            return AjaxResult.errorResult("请填写身份证号");
//        }
        String sexs = sex == 1 ? "男" : "女";
        if (ValidateUtil.isNull(city)) {
            city = cAgent.getCity();
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("市不能为空");
            }
        }

        Long postmanAgentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(username);
        if (null != postmanAgentId && 0 != postmanAgentId - agentId) {
            return AjaxResult.errorResult("该配送员已存在于其他代理下，请查证或更换账号");
        }


        //检测用户是否已经存在
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {//系统中无该用户 则新建
            UserInfo u = new UserInfo(UserType.POSTMAN, username, name, signature, telPhone, phone2, sexs,
                    province, city, county, address, user.getUsername());
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = username.substring(5, 11);
                }
                ResultInfo resultInfo = User.addUser(u, psw);
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }

        } else {//修改为配送员
            if (UserType.POSTMAN != userInfo.getUserType()) {
                User.modifyUserBaseInfo(username, Optional.ofNullable(name).orElse(""), null, null, UserType.POSTMAN);
//                User.modifyUserType(username, UserType.POSTMAN);
            }
        }

//        userInfo = UserInfoMemory.getInstance().getUserInfo(username);

        Long time = DateUtils.getCurrTime();
        if (ValidateUtil.isNotAbsInteger(type)) {
            type = 1;
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == postman) {
            //添加对应的权限
            CityPostman cityPostman = new CityPostman(username, province, city, county, region, "", user.getUsername(), time);
            cityPostman.setType(type);
            // cityPostman.setIsVerify(1);
            if (SYS_SETTINGS.POSTMAN_MUST_VERIFY != null && SYS_SETTINGS.POSTMAN_MUST_VERIFY == 1) {
                if (SYS_SETTINGS.MANAGER_POSTMAN_NEED_VERIFY == 1) {

                } else {
                    cityPostman.setIsVerify(1);
                }
            } else {
                cityPostman.setIsVerify(1);
            }
            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                cityPostman.setBusinessUsername(user.getUsername());
            }

            //转成英文城市名称
            if (ValidateUtil.isNotNull(city)) {
                cityPostman.setCityEN(JYPinyinHelper.toHanyuPinyin(city));
            }

            try {
                PostmanMan.updatePostmanVerify(user, info, fileUploadInfo);
                UserDaoSql.getInstance().insertObj(PojoTables.CityPostman, cityPostman);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后再试");
            }
            //缓存中新增
            CityPostmanMemory.getInstance().add(time);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_ADD).setLong01(time);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
            postman = CityPostmanMemory.getInstance().getPostman(username);
        }
        // 添加配送员与配送类型之间的关系
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            // 配送员与类型之间的关系
            PostmanMan.addPostmanTypeRelation(postman.getUsername(), postman.getType(), carTipId, user.getUsername());
            // 配送员与默认公司的管理
            // PostmanMan.addPostmanPlateCompany(postman.getUsername(), postman.getCity(), postman.getType(), user.getUsername());
        }


        //添加代理对应的配送员关系
        PostmanAgentRelation relation = new PostmanAgentRelation();
        relation.setAgentId(agentId);
        relation.setAgentUsername(cAgent.getUsername());
        relation.setPostmanUsername(username);
        if (null != postman) {
            relation.setPostmanId(postman.getId());
        }
        relation.setCreateTime(time);
        relation.setDelFlag(0);
        relation.setProvince(province);
        relation.setCity(city);
        relation.setCounty(county);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.POSTMAN_AGENT_RELATION, relation);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("条件代理关系时失败，请稍后再试");
        }
        PostmanAgentRelationMemory.getInstance().add(agentId);
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD).setLong01(agentId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    // 删除配送员
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/delete")
    @ResponseBody
    public String city_postman_delete(String token, Long agentId, String username, String city, String province, String county) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("代理ID不能为空");
        }
        CityAgent cAgent = CityAgentMemory.getInstance().getById(agentId);
        if (null == cAgent) {
            return AjaxResult.errorResult("您不是代理，无权新增");
        }

        if (ValidateUtil.isNull(city)) {
            city = cAgent.getCity();
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("市不能为空");
            }
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        String users = username.replace(",", "','");
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" set delFlag = 1,updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and agentId = ").append(agentId)
                .append(" and postmanUsername in ('").append(users).append("')");

        StringBuilder sbCity = new StringBuilder();
        sbCity.append("update ").append(PojoTables.CityPostman).append(" set delFlag = 1,updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and city = '")
                .append(city).append("' and username in ('").append(users).append("')");

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sbCity.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //在缓存中删除
        CityPostmanMemory.getInstance().reloadCity(city);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        //删除代理对应的派送员信息
        PostmanAgentRelationMemory.getInstance().reloadByAgentId(agentId);
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_RELOAD_BY_AGENT).setLong01(agentId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        // 修改用户类型
        User.delRevertUserStr(username);

        return AjaxResult.successResult();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/relation/add-up-del")
    @ResponseBody
    public String city_postman_relation_add(String token, String agentIds, String postman) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (StringUtils.isEmpty(postman)) {
            return AjaxResult.errorResult("骑手账号不能为空");
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postman);
        if (cityPostman == null) {
            return AjaxResult.errorResult("骑手信息不存在,请核实");
        }
        ResultInfo resultInfo = PostmanMan.dealPostmanAgentRelation(cityPostman, agentIds);
        if (resultInfo == null) {
            return AjaxResult.errorResult("处理失败,请稍后重试");
        }
        if (resultInfo != null && !resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        // 处理成功
        return AjaxResult.successResult();
    }

    // 获取骑手服务的商圈
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/cityAgent/list")
    @ResponseBody
    public String city_postman_relation_list(String token, String postman) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (StringUtils.isEmpty(postman)) {
            return AjaxResult.errorResult("骑手账号不能为空");
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postman);
        if (cityPostman == null) {
            return AjaxResult.errorResult("骑手信息不存在,请核实");
        }
        // 获取骑手服务的商圈
        ResultInfo resultInfo = PostmanMan.listCityAgentByPostmanService(cityPostman);
        if (resultInfo == null) {
            return AjaxResult.errorResult("获取失败，请稍后重试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        if (resultInfo.getObj() != null) {
            List<CityAgentVO> list = (ArrayList<CityAgentVO>) resultInfo.getObj();
            return AjaxResult.successResult(list.size(), list);
        }
        // 处理成功
        return AjaxResult.successResult();
    }


    //--------骑手端
    // 骑手获取同商圈骑手列表
    @RequestMapping(method = RequestMethod.POST, value = "/postman/agent/postman/list")
    @ResponseBody
    public String agent_postman_list(String token, Long companyId, String orderNo, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman requestCityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == requestCityPostman) {
            return AjaxResult.errorResult("您不是骑手，无法获取");
        }
        Integer type = requestCityPostman.getType();
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        List<String> list = null;
        if (ValidateUtil.isNotNull(orderNo) && SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1) {
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            if (info == null) {
                return AjaxResult.errorResult("未获取到地订单信息");
            }
            ShopInfo shopInfo = null;
            if (info.getIsShopPaoTuiOrder() != null && info.getIsShopPaoTuiOrder() == 1) {
                shopInfo = ShopMemory.getInstance().getShopByUsername(info.getUsername());
            } else {
                shopInfo = ShopMemory.getInstance().getShopById(info.getShopId());
            }
            if (shopInfo == null) {
                return AjaxResult.errorResult("未获取到商家信息");
            }
            list = PostmanShopRelationMemory.getInstance().listShopPostManListByShopUsername(shopInfo.getOwnUsername());
        } else if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            // 一乙系统
            PostCompanyInfo postCompanyInfo = null;
            if (companyId == null) {
                return AjaxResult.errorResult("公司id为空");
            } else {
                postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
            }
            if (postCompanyInfo == null) {
                return AjaxResult.errorResult("未获取到配送公司信息");
            }
            List<PostmanSignCompanyInfo> signCompanyInfoList = PostmanSignCompanyMemory.getInstance().listOfCompanyId(companyId, null, type, SIGN_COMPANY_STATUS.pass);
            list = signCompanyInfoList == null ? null : signCompanyInfoList.stream().filter(u -> u.getUsername() != null && StringUtils.isNotEmpty(u.getUsername()))
                    .map(u -> u.getUsername()).collect(Collectors.toList());
        } else {
            // 获取骑手所属商圈
            Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
            if (ValidateUtil.isNotID(agentId)) {
                return AjaxResult.errorResult("未获取到您所在商圈");
            }
            list = PostmanAgentRelationMemory.getInstance().listOfAgentId(agentId);
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, 0, null);
        }
        List<CityPostmanVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String username = list.get(i);
            if (ValidateUtil.isNull(username)) {
                continue;
            }
            //配送员的上班状态
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
            if (null == cityPostman) {
                continue;
            }

            // 自己的话过滤掉
            if (user.getUsername().equalsIgnoreCase(cityPostman.getUsername())) {
                continue;
            }

            if (null != type && null != cityPostman.getType() && 0 != cityPostman.getType() - type) {
                continue;
            }
            if (0 == 1 - cityPostman.getIsLock()) {
                continue;
            }
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 != 1 - cityPostman.getIsVerify()) {
                continue;
            }
            // 上班中的骑手
            if (0 != POSTMAN_WORK_STATUS.POSTMAN_WORK - cityPostman.getIsWork()) {
                continue;
            }

            //配送员的个人信息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
            if (null == userInfo) {
                continue;
            }

            // 实名认证通过
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && null != userInfo.getIsCert() && 0 != 1 - userInfo.getIsCert()) {
                continue;
            }

            CityPostmanVO cityPostmanVO = new CityPostmanVO();
            try {
                ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null != cityPostman) {
                cityPostmanVO.setIsWork(cityPostman.getIsWork());
            }

            cityPostmanVO.setType(cityPostman.getType());
            voList.add(cityPostmanVO);
        }
        if (ValidateUtil.isAbsList(voList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    //--------骑手端
    // 骑手获取骑手列表
    @RequestMapping(method = RequestMethod.POST, value = "/postman/city/postman/list")
    @ResponseBody
    public String city_postman_list(String token, Long companyId,
                                    Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman requestCityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == requestCityPostman) {
            return AjaxResult.errorResult("您不是骑手，无法获取");
        }
        Integer type = requestCityPostman.getType();
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        List<String> list = null;
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            // 一乙系统
            PostCompanyInfo postCompanyInfo = null;
            if (companyId == null) {
                return AjaxResult.errorResult("公司id为空");
            } else {
                postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
            }
            if (postCompanyInfo == null) {
                return AjaxResult.errorResult("未获取到配送公司信息");
            }
            List<PostmanSignCompanyInfo> signCompanyInfoList = PostmanSignCompanyMemory.getInstance().listOfCompanyId(companyId, null, type, SIGN_COMPANY_STATUS.pass);
            list = signCompanyInfoList == null ? null : signCompanyInfoList.stream().filter(u -> u.getUsername() != null && StringUtils.isNotEmpty(u.getUsername()))
                    .map(u -> u.getUsername()).collect(Collectors.toList());
        } else {
            if (SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT != null && SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT == 2) {
                Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
                if (ValidateUtil.isNotID(agentId)) {
                    return AjaxResult.errorResult("未获取到您所在商圈");
                }
                list = PostmanAgentRelationMemory.getInstance().listOfAgentId(agentId);
            } else {
//                List<CityPostman> postmanList = CityPostmanMemory.getInstance().listOfCity(requestCityPostman.getCity());
                List<CityPostman> postmanList = CityPostmanMemory.getInstance().listOfCity(requestCityPostman.getCity(), 2, null, null, null, null, null, null);
                if (postmanList != null && !postmanList.isEmpty()) {
                    list = postmanList.stream().map(bean -> bean.getUsername()).collect(Collectors.toList());
                }
            }
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(null, 0);
        }
        List<CityPostmanVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String username = list.get(i);
            if (ValidateUtil.isNull(username)) {
                continue;
            }
            //配送员的上班状态
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
            if (null == cityPostman) {
                continue;
            }

            // 自己的话过滤掉
            if (user.getUsername().equalsIgnoreCase(cityPostman.getUsername())) {
                continue;
            }

            if (null != type && null != cityPostman.getType() && 0 != cityPostman.getType() - type) {
                continue;
            }
            if (0 == 1 - cityPostman.getIsLock()) {
                continue;
            }
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 != 1 - cityPostman.getIsVerify()) {
                continue;
            }
            // 上班中的骑手
            if (0 != POSTMAN_WORK_STATUS.POSTMAN_WORK - cityPostman.getIsWork()) {
                continue;
            }

            //配送员的个人信息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
            if (null == userInfo) {
                continue;
            }

            // 实名认证通过
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && null != userInfo.getIsCert() && 0 != 1 - userInfo.getIsCert()) {
                continue;
            }

            CityPostmanVO cityPostmanVO = new CityPostmanVO();
            try {
                ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null != cityPostman) {
                cityPostmanVO.setIsWork(cityPostman.getIsWork());
            }

            cityPostmanVO.setType(cityPostman.getType());
            voList.add(cityPostmanVO);
        }
        if (ValidateUtil.isAbsList(voList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                return AjaxResult.successResult(voList, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    //--------------------------------城市配送员管理
    //获取配送员列表及对应的位置
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/position/list")
    @ResponseBody
    public String city_postman_list(String token,
                                    String city, String province, String county, String region,
                                    String username, String name,
                                    String companyIds, Integer type,
                                    Double lat, Double lng,
                                    String orderNo,
                                    Integer isCityAgent,  //是否按代理获取 0否 1是
                                    Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        List<CityPostman> list = null;
        // 若传过来公司  那么直接取到公司的配送员信息
        if (StringUtils.isNotEmpty(companyIds) && type != null && SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            Set<Long> set = CommonUtils.splitToSet(companyIds, Long.class);
            Set<String> postmanSet = new HashSet<>();
            for (Long id : set) {
                List<PostmanSignCompanyInfo> signCompanyInfos = PostmanSignCompanyMemory.getInstance().listOfCompanyId(id, null, type, SIGN_COMPANY_STATUS.pass);
                if (signCompanyInfos != null) {
                    Set<String> postmanTmpSet = signCompanyInfos.stream().filter(a -> a.getUsername() != null && StringUtils.isNotEmpty(a.getUsername())).map(a -> a.getUsername()).collect(Collectors.toSet());
                    if (postmanTmpSet != null && !postmanTmpSet.isEmpty()) {
                        postmanSet.addAll(postmanTmpSet);
                    }
                }
            }
            if (postmanSet != null) {
                list = postmanSet.stream().map(postman -> CityPostmanMemory.getInstance().getPostman(postman)).collect(Collectors.toList());
            }
        } else {
            // 根据城代获取所管理的商圈下的配送（代理可以管理多个商圈）
            String cityAdminUsername = user.getUsername();
            if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(user.getUsername())) {
                cityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(cityAdminUsername);
            }
            OrderInfo orderInfo = null;
            if (ValidateUtil.isNotNull(orderNo)) {
                orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            }
            if (SYS_SETTINGS.POSTMAN_SERVICE_SHOP != null && SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1
                    && OrderMan.isPostmanServicesShopOrder(orderInfo)) {
                ShopInfo shopInfo = null;
                if (orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS == 0) {
                    shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
                } else {
                    shopInfo = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
                }
                if (shopInfo == null) {
                    return AjaxResult.successResult(null, 0);
                }
                list = PostmanMan.listPostmanByServiceShop(shopInfo.getOwnUsername(), 2);
            } else if (null != isCityAgent && isCityAgent - 1 == 0) {
                list = PostmanMan.listOfAgent(cityAdminUsername, 2);
            } else {
                list = CityPostmanMemory.getInstance().listOfCity(city, 2, null, null, null, null, null, null);// 2全部
            }
        }
        if (ValidateUtil.isAbsList(list)) {
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityPostman cityPostman = list.get(i);
                if (null == cityPostman) {
                    continue;
                }

                //认证
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                        && (null == cityPostman.getIsVerify() || 0 != 1 - cityPostman.getIsVerify())) {
                    continue;
                }
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
                    UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
                    if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                        //已认证
                    } else {
                        continue;
                    }
                }

                //押金
                if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
                    // 必须缴纳
                    //验证押金金额是否满足
                    UserWallet userWallet = UserWalletMemory.getInstance().getWallet(cityPostman.getUsername());
                    if (null == userWallet) {
                        continue;
                    }
                    if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                        continue;
                    }
                    //必须缴纳的押金金额
                    Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
                    if (null == money) {
                        money = 0d;
                    }

                    if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                        continue;
                    }
                }

                CityPostmanVO vo = PostmanMan.getOne(cityPostman);
                if (null == vo) {
                    continue;
                }

                if (ValidateUtil.isNotNull(username) && !vo.getUsername().equals(username)) {
                    continue;
                }
                if (ValidateUtil.isNotNull(name) && !vo.getName().equals(name)) {
                    continue;
                }

                //获取配送员位置信息
                PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(vo.getId());
                if (null != info) {
                    Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(vo.getUsername());
                    if (ValidateUtil.isAbsInteger(count)) {
                        info.setOrderCount(count);
                    }
                    //距离
                    if (ValidateUtil.isLatLng(lat, lng)
                            && ValidateUtil.isLatLng(info.getLat(), info.getLng())) {
                        Double distinct = Geohash.distance(lat, lng, info.getLat(), info.getLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            vo.setDistinct(distinct);
                        }
                    }
                }
                vo.setPositionInfo(info);//配送员所在的位置
                voList.add(vo);
            }

            if (ValidateUtil.isAbsList(voList)) {
                Collections.sort(voList, new Comparator<CityPostmanVO>() {
                    // 先按距离升序，序号相同 则空闲升序
                    public int compare(CityPostmanVO arg0, CityPostmanVO arg1) {
                        if (arg1.getDistinct().compareTo(arg0.getDistinct()) == 0) {
                            return arg1.getDistinct().compareTo(arg0.getDistinct()) > 0 ? 1 : -1;
                        } else {
                            return (int) (arg0.getPositionInfo().getOrderCount() - arg1.getPositionInfo().getOrderCount());
                        }
                    }
                });
            }
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                return AjaxResult.successResult(pageList.list, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    //==========================
    // 配送员下拉框
    @RequestMapping(method = RequestMethod.POST, value = "/admin/postman/select")
    @ResponseBody
    public String user_agent_select(String token, String cityUsername, String city) {
        //验证用户有效性
        List<CityPostman> list = null;
        if (ValidateUtil.isNotNull(cityUsername)) {
            if (ValidateUtil.isNull(cityUsername)) {
                return AjaxResult.errorResult("账号不能为空");
            }
            list = PostmanMan.listOfAgent(cityUsername, 2);
        } else {
            if (ValidateUtil.isNull(city)) {
                return AjaxResult.errorResult("城市不能为空");
            }
//            list = CityPostmanMemory.getInstance().listOfCity(city);
            list = CityPostmanMemory.getInstance().listOfCity(city, 2, null, null, null, null, null, null);
        }
        List<Object> re = null;
        if (ValidateUtil.isAbsList(list)) {
            re = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(list.get(i).getUsername());
                if (null == userInfo) {
                    continue;
                }
                Map<String, Object> data = new HashMap<>();
                data.put("username", list.get(i).getUsername());
                data.put("name", userInfo.getName());
                re.add(data);
            }
            if (ValidateUtil.isAbsList(re)) {
                return AjaxResult.successResult(re.size(), re);
            }
        }
        return AjaxResult.successResult(0, null);
    }


    //--------------------------其他
    // 获取指定配送员的排行榜信息
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/statistics/list")
    @ResponseBody
    public String postman_pai_hang(String token, String city, Long agentId, Long startTime, Long endTime, Integer
            page, Integer size) {

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("城市不能为空");
        }
        if (city.contains("市")) {
            city = city.substring(0, city.indexOf("市"));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("城市不能为空");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //
        List<String> list = null;
        if (ValidateUtil.isID(agentId)) {
            list = PostmanAgentRelationMemory.getInstance().listOfAgentId(agentId);
        } else {
            list = listOfPostmanUsernameByCity(city);
        }
        if (ValidateUtil.isAbsList(list)) {
            String postmanStr = getListToString(list);
            if (ValidateUtil.isNull(postmanStr)) {
                return AjaxResult.successResult(0, null);
            }
//            SELECT
//            p.username,
//                    S_.postmanName AS postmanName,
//            S_.postmanImageUrl AS postmanImageUrl,
//                    IFNULL(S_.orderCount,0),
//                    IFNULL(S_.postmanMoney,0)
//            FROM
//            city_postman AS p
//            LEFT JOIN
//            (SELECT
//            Info.postmanUsername AS postman,
//                    Info.postmanName AS postmanName,
//            Info.postmanImageUrl AS postmanImageUrl,
//                    COUNT(INFO.OrderNO) AS orderCount,
//            SUM(IFNULL(PAY.postmanMoney, 0)) AS postmanMoney
//            FROM
//            order_info AS INFO
//            LEFT JOIN order_pay AS PAY
//            ON INFO.orderNo = PAY.orderNo
//            WHERE orderStatus = 9
//            AND INFO.delFlag = 0
//            AND INFO.isRefundApply != 2
//            AND INFO.isRefundApply != 1
//            AND INFO.createTimE > 0
//            AND INFO.createTime < 1555296104000
//            AND INFO.isZiQu = 0
//            AND INFO.shopSelfPost = 0
//            AND INFO.postmanUsername IS NOT NULL
//            AND PAY.isOrderCancel = 0
//            AND Pay.isPaid = 1
//            AND Pay.postman IS NOT NULL
//            AND Info.postmanUsername IN (14122226666,13122221111)
//            GROUP BY Info.postmanUsername) AS S_ ON p.username = S_.postman
//            WHERE P.username IN (14122226666,13122221111)
//
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT ")
                    .append("  p.username as postman,")
                    .append("  IFNULL(S_.orderCount,0) as orderCount,  ")
                    .append("  IFNULL(S_.postmanMoney,0) as postmanMoney ")
                    .append(" FROM ").append(PojoTables.CityPostman).append(" as p ")
                    .append(" Left Join ").append("(");
            sql.append("select                                      ")
                    .append("   Info.postmanUsername    AS    postman,        ")
                    .append("   COUNT(INFO.OrderNO)     AS    orderCount,     ")
                    .append("   SUM(IFNULL(PAY.postmanMoney,0)) AS postmanMoney ")
                    .append("FROM                       ")
                    .append(PojoTables.OrderInfo).append(" as INFO          ")
                    .append("Left join ").append(PojoTables.OrderPay).append(" as PAY ")
                    .append("   on INFO.orderNo = PAY.orderNo       ")
                    .append(" where ")
                    .append(" orderStatus =").append(ORDER_STATUS.OVER)
                    .append(" AND INFO.delFlag = 0  ")
                    .append(" AND INFO.isRefundApply != 2  ")
                    .append(" AND INFO.isRefundApply != 1  ");
            if (ValidateUtil.isAbsLong(startTime)) {
                sql.append(" AND INFO.createTime >= ").append(startTime);
            }
            if (ValidateUtil.isAbsLong(endTime)) {
                sql.append(" AND INFO.createTime < ").append(endTime);
            }
            sql.append(" AND INFO.isZiQu = 0  ")
                    .append("  AND INFO.shopSelfPost = 0  ")
                    .append("  AND INFO.postmanUsername IS NOT NULL ")
                    .append("  AND PAY.isOrderCancel =0   ")
                    .append("  AND Pay.isPaid = 1     ")
                    .append("  AND Pay.postman IS NOT NULL ")
                    .append("  AND Info.postmanUsername IN  ").append(postmanStr)
                    .append("  GROUP BY Info.postmanUsername  ");
            sql.append(")").append(" AS S_ ON p.username = S_.postman ")
                    .append(" WHERE P.username IN ").append(postmanStr);

            List<HashMap<String, Object>> dbList = null;
            try {
                dbList = UserDaoSql.getInstance().queryBySql(sql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            if (!ValidateUtil.isAbsList(dbList)) {
                return AjaxResult.successResult(0, null);
            }
            for (HashMap<String, Object> map : dbList) {
                if (ValidateUtil.isNull(map.get("orderCount"))) {
                    map.put("orderCount", 0);
                }
            }
            // 排序
            dbList.sort(new Comparator<HashMap<String, Object>>() {
                @Override
                public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
                    return Integer.parseInt(o2.get("orderCount").toString()) - Integer.parseInt(o1.get("orderCount").toString());
                }
            });
            JYPageUtils.PageList pageList = JYPageUtils.getList(dbList, page, size);
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        }
        return AjaxResult.successResult(0, 0, null);
    }


    // （3,2，。。）的形式
    private static String getListToString(List<String> list) {
        if (ValidateUtil.isAbsList(list)) {
            boolean flag = false;
            StringBuffer sq = new StringBuffer();
            sq.append("(");
            for (String temp : list) {
                if (ValidateUtil.isNotNull(temp)) {
                    sq.append(temp).append(",");
                    flag = true;
                }
            }
            String r = sq.toString();
            if (flag && r.endsWith(",")) {
                r = r.substring(0, r.length() - 1);
            }
            if (flag) {
                return r + ")";
            }
        }
        return null;
    }


    // 获取该城市的配送员信息
    private static List<String> listOfPostmanUsernameByCity(String city) {
        if (ValidateUtil.isNull(city)) {
            return null;
        }
//        List<CityPostman> cityPostmen = CityPostmanMemory.getInstance().listOfCity(city);
        List<CityPostman> cityPostmen = CityPostmanMemory.getInstance().listOfCity(city, 2, null, null, null, null, null, null);
        if (ValidateUtil.isAbsList(cityPostmen)) {
            return cityPostmen.stream().map(CityPostman::getUsername).collect(Collectors.toList());
        }
        return null;
    }


    //获取一条
    private CityPostmanVO addOne(CityPostman cityPostman) {
        if (null == cityPostman) {
            return null;
        }
        if (ValidateUtil.isNull(cityPostman.getUsername())) {
            return null;
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
        if (null == userInfo) {
            return null;
        }
        CityPostmanVO cityPostmanVo = new CityPostmanVO();
        try {
            ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVo, null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        cityPostmanVo.setIsCert(userInfo.getIsCert());
        cityPostmanVo.setApplyTime(cityPostman.getApplyTime());
        cityPostmanVo.setVerifyTime(cityPostman.getVerifyTime());
        cityPostmanVo.setIsVerify(cityPostman.getIsVerify());
        cityPostmanVo.setIsWork(cityPostman.getIsWork());
        cityPostmanVo.setId(cityPostman.getId());
        cityPostmanVo.setIsLock(cityPostman.getIsLock());
        cityPostmanVo.setProvince(cityPostman.getProvince());
        cityPostmanVo.setCity(cityPostman.getCity());
        cityPostmanVo.setCounty(cityPostman.getCounty());
        cityPostmanVo.setShopId(cityPostman.getShopId());
        cityPostmanVo.setType(cityPostman.getType());
        cityPostmanVo.setOnlineTimeStr(cityPostman.getOnlineTimeStr());
        if (ValidateUtil.isNotNull(cityPostmanVo.getSignPhoto()) && ValidateUtil.isNotNetUrl(cityPostmanVo.getSignPhoto())) {
            cityPostmanVo.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + cityPostmanVo.getSignPhoto());
        }
        if (StringUtils.isNotEmpty(cityPostmanVo.getUsername())) {
            UserWallet wallet = UserWalletMemory.getInstance().getWallet(cityPostmanVo.getUsername());
            cityPostmanVo.setDepositMoney(Optional.ofNullable(wallet).map(bean -> bean.getDepositMoney()).isPresent() ? wallet.getDepositMoney() : 0.0d);
        }

        return cityPostmanVo;
    }


    //----------------骑手锁定问题
    @RequestMapping(value = "admin/postman/lock-unlock", method = RequestMethod.POST)
    @ResponseBody
    public String postman_isLock(String token, String postman, Integer isLock) {
        //
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (isLock == null || (isLock != 0 && isLock != 1)) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        if (ValidateUtil.isNull(postman)) {
            return AjaxResult.errorResult("请选择配送员");
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postman);
        if (cityPostman == null) {
            return AjaxResult.errorResult("配送员信息不存在");
        }
        if (cityPostman.getIsLock() != null && cityPostman.getIsLock() == isLock) {
            return AjaxResult.successResult();
        }
        // 锁定了就要下班
        String isWork = "";
        if (isLock == 1) {
            isWork = ",isWork= 0";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.CityPostman).append(" set isLock = ").append(isLock).append(isWork).append(",updateUser = '").append(user.getUsername()).append("' where delFlag = 0 ")
                .append(" and username = '").append(postman).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("停用/启用骑手失败，请稍后再试");
        }
        CityPostmanMemory.getInstance().modifyByUsername(postman);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(postman);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    // *************************公司获取骑手********************************
    //
    @RequestMapping(value = "company/postman/type/list")
    @ResponseBody
    public String companyPostmanTypeList(String token, Long companyId, Integer type
            , @RequestParam(value = "page", defaultValue = "1") Integer page
            , @RequestParam(value = "size", defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (type == null) {
            return AjaxResult.errorResult("类型不能为空");
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            postCompanyInfo = PostCompanyMemory.getInstance().getByUsername(user.getUsername());
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }
        List<PostmanSignCompanyInfo> signCompanyInfoList = PostmanSignCompanyMemory.getInstance().listOfCompanyId(companyId, null, type, SIGN_COMPANY_STATUS.pass);
        List<CityPostman> list = signCompanyInfoList == null ? null : signCompanyInfoList.stream().filter(u -> u.getUsername() != null && StringUtils.isNotEmpty(u.getUsername()))
                .map(u -> CityPostmanMemory.getInstance().getPostman(u.getUsername())).filter(a -> a.getType() == type && a.getIsWork() == 1 && (a.getIsLock() == null || a.getIsLock() == 0)).collect(Collectors.toList());
        if (list == null || list.isEmpty()) {
            return AjaxResult.successResult(0, 0, null);
        }
        List<CityPostmanVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CityPostman cityPostman = list.get(i);
            if (null == cityPostman) {
                continue;
            }
            if (null != type && null != cityPostman.getType() && 0 != cityPostman.getType() - type) {
                continue;
            }
            if (0 == 1 - cityPostman.getIsLock()) {
                continue;
            }
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 != 1 - cityPostman.getIsVerify()) {
                continue;
            }
            // 上班中的骑手
            if (0 != POSTMAN_WORK_STATUS.POSTMAN_WORK - cityPostman.getIsWork()) {
                continue;
            }
            //配送员的个人信息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
            if (null == userInfo) {
                continue;
            }
            // 实名认证通过
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && null != userInfo.getIsCert() && 0 != 1 - userInfo.getIsCert()) {
                continue;
            }
            CityPostmanVO cityPostmanVO = new CityPostmanVO();
            try {
                ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null != cityPostman) {
                cityPostmanVO.setIsWork(cityPostman.getIsWork());
            }
            cityPostmanVO.setType(cityPostman.getType());
            voList.add(cityPostmanVO);
        }
        if (ValidateUtil.isAbsList(voList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 骑手转单获取同一个公司的骑手列表
    @RequestMapping(value = "postman/company/postman/type/list")
    @ResponseBody
    public String postmanCompanyPostmanTypeList(String token, Long companyId, Integer type
            , @RequestParam(value = "page", defaultValue = "1") Integer page
            , @RequestParam(value = "size", defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (type == null) {
            return AjaxResult.errorResult("类型不能为空");
        }
        PostCompanyInfo postCompanyInfo = null;
        if (companyId == null) {
            return AjaxResult.errorResult("公司id为空");
        } else {
            postCompanyInfo = PostCompanyMemory.getInstance().getById(companyId);
        }
        if (postCompanyInfo == null) {
            return AjaxResult.errorResult("未获取到配送公司信息");
        }
        List<PostmanSignCompanyInfo> signCompanyInfoList = PostmanSignCompanyMemory.getInstance().listOfCompanyId(companyId, null, type, SIGN_COMPANY_STATUS.pass);
        List<CityPostman> list = signCompanyInfoList == null ? null : signCompanyInfoList.stream().filter(u -> u.getUsername() != null && StringUtils.isNotEmpty(u.getUsername()))
                .map(u -> CityPostmanMemory.getInstance().getPostman(u.getUsername())).collect(Collectors.toList());
        if (list == null || list.isEmpty()) {
            return AjaxResult.successResult(0, 0, null);
        }
        List<CityPostmanVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CityPostman cityPostman = list.get(i);
            if (null == cityPostman) {
                continue;
            }
            // 自己的话过滤掉
            if (user.getUsername().equalsIgnoreCase(cityPostman.getUsername())) {
                continue;
            }
            if (null != type && null != cityPostman.getType() && 0 != cityPostman.getType() - type) {
                continue;
            }
            if (0 == 1 - cityPostman.getIsLock()) {
                continue;
            }
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 != 1 - cityPostman.getIsVerify()) {
                continue;
            }
            // 上班中的骑手
            if (0 != POSTMAN_WORK_STATUS.POSTMAN_WORK - cityPostman.getIsWork()) {
                continue;
            }
            //配送员的个人信息
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
            if (null == userInfo) {
                continue;
            }
            // 实名认证通过
            if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && null != userInfo.getIsCert() && 0 != 1 - userInfo.getIsCert()) {
                continue;
            }
            CityPostmanVO cityPostmanVO = new CityPostmanVO();
            try {
                ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVO);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null != cityPostman) {
                cityPostmanVO.setIsWork(cityPostman.getIsWork());
            }
            cityPostmanVO.setType(cityPostman.getType());
            voList.add(cityPostmanVO);
        }
        if (ValidateUtil.isAbsList(voList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
                return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    @RequestMapping("/postman/city/postman/getList")
    @ResponseBody
    public String getPostman(String token,
                             String city, String province, String county, String region,
                             String username, String name,
                             String companyIds, Integer type,
                             Double lat, Double lng,
                             String orderNo,
                             Integer isCityAgent,  //是否按代理获取 0否 1是
                             Integer page, Integer size) {

        List<CityPostman> list = null;
        // 若传过来公司  那么直接取到公司的配送员信息
        if (StringUtils.isNotEmpty(companyIds) && type != null && SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            Set<Long> set = CommonUtils.splitToSet(companyIds, Long.class);
            Set<String> postmanSet = new HashSet<>();
            for (Long id : set) {
                List<PostmanSignCompanyInfo> signCompanyInfos = PostmanSignCompanyMemory.getInstance().listOfCompanyId(id, null, type, SIGN_COMPANY_STATUS.pass);
                if (signCompanyInfos != null) {
                    Set<String> postmanTmpSet = signCompanyInfos.stream().filter(a -> a.getUsername() != null && StringUtils.isNotEmpty(a.getUsername())).map(a -> a.getUsername()).collect(Collectors.toSet());
                    if (postmanTmpSet != null && !postmanTmpSet.isEmpty()) {
                        postmanSet.addAll(postmanTmpSet);
                    }
                }
            }
            if (postmanSet != null) {
                list = postmanSet.stream().map(postman -> CityPostmanMemory.getInstance().getPostman(postman)).collect(Collectors.toList());
            }
        } else {
            OrderInfo orderInfo = null;
            if (ValidateUtil.isNotNull(orderNo)) {
                orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
            }
            if (SYS_SETTINGS.POSTMAN_SERVICE_SHOP != null && SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1
                    && OrderMan.isPostmanServicesShopOrder(orderInfo)) {
                ShopInfo shopInfo = null;
                if (orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS == 0) {
                    shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
                } else {
                    shopInfo = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
                }
                if (shopInfo == null) {
                    return AjaxResult.successResult(null, 0);
                }
                list = PostmanMan.listPostmanByServiceShop(shopInfo.getOwnUsername(), 2);
            } else {
                list = CityPostmanMemory.getInstance().listOfCity(city, 2, null, null, null, null, null, null);// 2全部
            }
        }
        if (ValidateUtil.isAbsList(list)) {
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityPostman cityPostman = list.get(i);
                if (null == cityPostman) {
                    continue;
                }

                CityPostmanVO vo = PostmanMan.getOne(cityPostman);
                if (null == vo) {
                    continue;
                }

                if (ValidateUtil.isNotNull(username) && !vo.getUsername().equals(username)) {
                    continue;
                }
                if (ValidateUtil.isNotNull(name) && !vo.getName().equals(name)) {
                    continue;
                }

                //获取配送员位置信息
                PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(vo.getId());
                if (null != info) {
                    Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(vo.getUsername());
                    if (ValidateUtil.isAbsInteger(count)) {
                        info.setOrderCount(count);
                    }
                    //距离
                    if (ValidateUtil.isLatLng(lat, lng)
                            && ValidateUtil.isLatLng(info.getLat(), info.getLng())) {
                        // TODO 暂时写死试试效果
                        String distinctStr = AMapUtils.getRideDistinct("c018debba4451fe02ebc82827a15e674", lat, lng, info.getLat(), info.getLng());
                        Double distinct = Double.parseDouble(distinctStr);
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            vo.setDistinct(distinct);
                        }
                    }
                }
                vo.setPositionInfo(info);//配送员所在的位置
                voList.add(vo);
            }

            if (ValidateUtil.isAbsList(voList)) {
                Collections.sort(voList, new Comparator<CityPostmanVO>() {
                    // 先按距离升序，序号相同 则空闲升序
                    public int compare(CityPostmanVO arg0, CityPostmanVO arg1) {
                        if (arg1.getDistinct().compareTo(arg0.getDistinct()) == 0) {
                            return arg1.getDistinct().compareTo(arg0.getDistinct()) > 0 ? 1 : -1;
                        } else {
                            return (int) (arg0.getPositionInfo().getOrderCount() - arg1.getPositionInfo().getOrderCount());
                        }
                    }
                });
            }
            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                return AjaxResult.successResult(pageList.list, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }


    //新平台配送员新增（基于带商圈改造）
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/new/add")
    @ResponseBody
    public String city_postman_new_add(@RequestParam("username") String username,
                                       @RequestParam("name") String name,
                                       @RequestParam("idCard") String ownerID,
                                       @RequestParam("sex") Integer sex,
                                       @RequestParam("address") String address,
                                       @RequestParam("shopId") Long shopId,
                                       @RequestParam("accountName") String accountName,
                                       @RequestParam("emergencyContactPhone") String emergencyContactPhone,
                                       @RequestParam("emergencyContactName") String emergencyContactName,
                                       @RequestParam("bankName") String bankName,
                                       @RequestParam("city") String city,
                                       @RequestParam("province") String province,
                                       @RequestParam("provider") Long supplier,
                                       String county,
                                       String operationUserName,
                                       Long carTipId,
                                       String signature,
                                       String note,
                                       String phone2,
                                       Long honeycombId,
                                       FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(shopId)) {
            return AjaxResult.errorResult("门店不能为空");
        }

        //初始化审核表对象
        CityPostmanVerify info = new CityPostmanVerify();
        info.setOwnerID(ownerID);
        info.setSex(sex);
        info.setUsername(username);
        info.setName(name);
        info.setTelephone(username);


        //TODO 上传字段
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl1() != null) {
            info.setImageUrl1(fileUploadInfo.getImageUrl1());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl2() != null) {
            info.setImageUrl2(fileUploadInfo.getImageUrl2());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl9() != null) {
            info.setImageUrl9(fileUploadInfo.getImageUrl9());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl10() != null) {
            info.setImageUrl10(fileUploadInfo.getImageUrl10());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl11() != null) {
            info.setImageUrl11(fileUploadInfo.getImageUrl11());
        }

        //身份证名称 身份证号
        if (ValidateUtil.isNull(info.getOwner())) {
            info.setOwner(info.getName());
//            return AjaxResult.errorResult("请填写姓名");
        }
//        if (ValidateUtil.isNull(info.getOwnerID())) {
//            return AjaxResult.errorResult("请填写身份证号");
//        }
        String sexs = sex == 1 ? "男" : "女";

        // TODO 2021.05.28 直接判断存不存在，存在就走修改逻辑
//        Long postmanAgentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(username);


//        if (null != postmanAgentId && 0 != postmanAgentId - agentId) {
//            return AjaxResult.errorResult("该配送员已存在于其他代理下，请查证或更换账号");
//        }


        //检测用户是否已经存在
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == userInfo) {//系统中无该用户 则新建
            UserInfo u = new UserInfo(UserType.POSTMAN, username, name, signature, username, phone2, sexs,
                    province, city, county, address, user.getUsername());
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW) {
                    psw = username.substring(5, 11);
                }
                //TODO 此处添加用户会与下面事务不一致
                ResultInfo resultInfo = User.addUser(u, psw);
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } catch (Exception e) {
                return AjaxResult.errorResult("新增失败，请稍后再试");
            }

        } else {//修改为配送员
            return AjaxResult.errorResult("该登录账户已存在！");
//            if (UserType.POSTMAN != userInfo.getUserType()) {
//                User.modifyUserBaseInfo(username, Optional.ofNullable(name).orElse(""), null, null, UserType.POSTMAN);
////                User.modifyUserType(username, UserType.POSTMAN);
//            }
        }

//        userInfo = UserInfoMemory.getInstance().getUserInfo(username);

        Long time = DateUtils.getCurrTime();
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
        }
        if (null == postman) {
            //添加对应的权限
            CityPostman cityPostman = new CityPostman(username, province, city, county, null, "", user.getUsername(), time);
            cityPostman.setType(1);
            // cityPostman.setIsVerify(1);
            if (SYS_SETTINGS.POSTMAN_MUST_VERIFY != null && SYS_SETTINGS.POSTMAN_MUST_VERIFY == 1) {
                if (SYS_SETTINGS.MANAGER_POSTMAN_NEED_VERIFY == 1) {

                } else {
                    cityPostman.setIsVerify(1);
                }
            } else {
                cityPostman.setIsVerify(1);
            }
            if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
                cityPostman.setBusinessUsername(user.getUsername());
            }

            //转成英文城市名称
            if (ValidateUtil.isNotNull(city)) {
                cityPostman.setCityEN(JYPinyinHelper.toHanyuPinyin(city));
            }

            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
            }

            //TODO 新增骑手字段绑定
            //===============================================
            if (cityPostman != null && honeycombId != null) {
                cityPostman.setHoneycomb_id(honeycombId);
            }

            cityPostman.setBank_name(bankName);
            cityPostman.setAccount_name(accountName);
            cityPostman.setBank_account(bankName);
            cityPostman.setEmergency_contact_name(emergencyContactName);
            cityPostman.setEmergency_contact_phone(emergencyContactPhone);
            cityPostman.setSupplier_id(supplier);
            cityPostman.setIsWork(0);
            //===============================================

            try {
                if (StringUtils.isNotEmpty(note)) {
                    user.setNote(note);
                }
                PostmanMan.updatePostmanVerify(user, info, fileUploadInfo);
                Long postmanId  = UserDaoSql.getInstance().saveObj(PojoTables.CityPostman, cityPostman, conn);
                cityPostman.setId(postmanId);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍后再试");
            }


            //TODO 新增骑手时绑定店铺
            //==============================================
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);

            PostmanShopRelation p = setPostmanShopRelation(shopInfo, cityPostman, user.getUsername());
            try {
                UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_SHOP_RELATION, p, conn);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);        // 回滚
                UserDaoSql.getInstance().close(conn);
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }
            //骑手默认下班
            cityPostman.setIsWork(0);
            //===============================================

            try {
                conn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                return AjaxResult.errorResult("添加失败");
            } finally {
                UserDaoSql.getInstance().close(conn);
            }

            //刷新缓存
            PostmanShopRelationMemory.getInstance().run();

            //缓存中新增
            CityPostmanMemory.getInstance().add(time);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_ADD).setLong01(time);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
            postman = CityPostmanMemory.getInstance().getPostman(username);
        }
        // 添加配送员与配送类型之间的关系
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            // 配送员与类型之间的关系
            PostmanMan.addPostmanTypeRelation(postman.getUsername(), postman.getType(), carTipId, user.getUsername());
            // 配送员与默认公司的管理
            // PostmanMan.addPostmanPlateCompany(postman.getUsername(), postman.getCity(), postman.getType(), user.getUsername());
        }


        //添加代理对应的配送员关系
//        PostmanAgentRelation relation = new PostmanAgentRelation();
//        relation.setAgentId(agentId);
//        relation.setAgentUsername(cAgent.getUsername());
//        relation.setPostmanUsername(username);
//        if (null != postman) {
//            relation.setPostmanId(postman.getId());
//        }
//        relation.setCreateTime(time);
//        relation.setDelFlag(0);
//        relation.setProvince(province);
//        relation.setCity(city);
//        relation.setCounty(county);


//        try {
//            UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_AGENT_RELATION, relation,conn);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("条件代理关系时失败，请稍后再试");
//        }
        //TODO 因为无商圈所以去除商圈的缓存
//        PostmanAgentRelationMemory.getInstance().add(agentId);
        // 数据同步
//        try {
//            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD).setLong01(agentId);
//            JmsSender.setTopicSender(notify);
//        } catch (Exception e) {
//        }


        return AjaxResult.successResult();
    }

    //【新】修改配送员
    @RequestMapping(method = RequestMethod.POST, value = "/city/postman/new/modify")
    @ResponseBody
    public String city_postman_new_modify(CityPostmanVO info, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();

        if (null == info) {
            return AjaxResult.errorResult("输入信息有误，请查证");
        }

        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("市不能为空");
        }


        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(info.getUsername());
        if (null == cityPostman) {
            return AjaxResult.errorResult("该配送员已不存在，请查证");
        }

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(info.getUsername());
        if (null == userInfo) {
            return AjaxResult.errorResult("该配送员已不存在，请查证.");
        }

        if (null == info.getIsWork()) {
            info.setIsWork(cityPostman.getIsWork());
        }


        StringBuffer sb = new StringBuffer();
        boolean needUpdate = false;
        String isWork = "";
        //修改上班状态
        if (0 != info.getIsWork() - cityPostman.getIsWork()) {
            isWork = " isWork = " + info.getIsWork() + ",";

            needUpdate = true;
        }
        sb.append("update ").append(PojoTables.CityPostman).append(" set ").append(isWork).append(" updateUser='").append(user.getUsername()).append("'");

        if (ValidateUtil.isNotNull(info.getCity())) {
            needUpdate = true;
            sb.append(", province ='").append(info.getProvince()).append("'");
            sb.append(", city ='").append(info.getCity()).append("'");
            if (ValidateUtil.isNotNull(info.getCounty())) {
                sb.append(", county ='").append(info.getCounty()).append("'");
            } else {
                sb.append(", county =''");
            }
            if (info.getHoneycombId() != null) {
                sb.append(",honeycomb_id='").append(info.getHoneycombId()).append("'");
                // 改为机动骑手
                sb.append(",postman_type=2");
            }else{
                sb.append(",honeycomb_id=null");
                // 改为驻店骑手
                sb.append(",postman_type=1");
            }
            if (info.getProvider() != null) {
                sb.append(",supplier_id='").append(info.getProvider()).append("'");;
            }
            if (info.getBankName() != null) {
                sb.append(",bank_name='").append(info.getBankName()).append("'");;
            }
            if (info.getAccountName() != null) {
                sb.append(",account_name='").append(info.getAccountName()).append("'");;
            }
            if (info.getBankAccount() != null) {
                sb.append(",bank_account='").append(info.getBankAccount()).append("'");;
            }
            if (info.getEmergencyContactName() != null) {
                sb.append(",emergency_contact_name='").append(info.getEmergencyContactName()).append("'");
            }
            if (info.getEmergencyContactPhone() != null) {
                sb.append(",emergency_contact_phone='").append(info.getEmergencyContactPhone()).append("'");
            }
        }
        sb.append(" where delFlag=0 and username='").append(info.getUsername()).append("' ");
        if (needUpdate) {
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改工人的工作状态时出错，请稍后再试");
            }
            // 清除缓存
            CityPostmanMemory.getInstance().modifyByUsername(info.getUsername());

            if (ValidateUtil.isNotNull(info.getCity())) {
                // 重新加载
                CityPostmanMemory.getInstance().reloadCity(info.getCity());
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(info.getCity());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            } else {
                CityPostmanMemory.getInstance().modifyByUsername(cityPostman.getUsername());
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_INFO_MODIFY).setStr01(info.getUsername());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }

        }

        if (ValidateUtil.isNotNull(info.getCity())) {
            String province = info.getProvince();
            if (ValidateUtil.isNull(province)) {
                province = "";
            }
            String city = info.getCity();
            if (ValidateUtil.isNull(city)) {
                city = "";
            }
            String county = info.getCounty();
            if (ValidateUtil.isNull(county)) {
                county = "";
            }
            // 修改用户信息
            StringBuffer sbU = new StringBuffer();
            sbU.append("update ").append(PojoTables.UserInfo).append(" set province='").append(province)
                    .append("',city='").append(city).append("',county='").append(county).append("',updateUser='")
                    .append(user.getUsername());
            if(info.getNote()!=null){
                sbU.append("',note='").append(info.getNote());
            }
            if(info.getAddress()!=null){
                sbU.append("',address='").append(info.getAddress());
            }
            sbU.append("' where delFlag =0 and username = '").append(info.getUsername()).append("'");

            try {
                UserDaoSql.getInstance().executeBySql(sbU.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            UserInfoMemory.getInstance().modifyUserInfo(info.getUsername());
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.USER_INFO_MODIFY).setStr01(info.getUsername());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }

        //TODO 保存图片
        //==============================================
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl1() != null) {
            info.setImageUrl1(fileUploadInfo.getImageUrl1());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl2() != null) {
            info.setImageUrl2(fileUploadInfo.getImageUrl2());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl9() != null) {
            info.setImageUrl9(fileUploadInfo.getImageUrl9());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl10() != null) {
            info.setImageUrl10(fileUploadInfo.getImageUrl10());
        }
        if (fileUploadInfo != null && fileUploadInfo.getImageUrl11() != null) {
            info.setImageUrl11(fileUploadInfo.getImageUrl11());
        }
        //==============================================


        //修改工人的信息
        User.modifyUserInfo(info.getUsername(), info.getName(), info.getSignPhoto(),
                info.getSex(), info.getTelPhone(), user.getUsername(),info.getNote());

        CityPostmanVerify cityPostmanVerify = new CityPostmanVerify();
        cityPostmanVerify.setUsername(info.getUsername());
        cityPostmanVerify.setName(info.getName());
        cityPostmanVerify.setSex(info.getSex() == "男" ? 1 : 2);
        cityPostmanVerify.setTelephone(info.getTelPhone());
        cityPostmanVerify.setImageUrl1(info.getImageUrl1());
        cityPostmanVerify.setImageUrl2(info.getImageUrl2());
        cityPostmanVerify.setImageUrl3(info.getImageUrl3());
        cityPostmanVerify.setImageUrl4(info.getImageUrl4());
        cityPostmanVerify.setImageUrl9(info.getImageUrl9());
        cityPostmanVerify.setImageUrl10(info.getImageUrl10());
        cityPostmanVerify.setImageUrl11(info.getImageUrl11());
        cityPostmanVerify.setOwnerID(info.getIdCard());
        try {
            PostmanMan.updatePostmanVerify(user, cityPostmanVerify, fileUploadInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        // 需要执行的sql
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        //TODO 修改骑手时绑定店铺
        //==============================================
        StringBuffer sb2 = new StringBuffer();
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(info.getShopId());
        PostmanShopRelation ps = setPostmanShopRelation(shopInfo, cityPostman, user.getUsername());
        sb2.append("update ").append(PojoTables.POSTMAN_SHOP_RELATION).append(" set delFlag = 1 ").append(" where postmanUsername IN ('").append(info.getUsername()).append("')");
        try {
            UserDaoSql.getInstance().executeBySql(sb2.toString(), conn);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);        // 回滚
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        try {
            UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_SHOP_RELATION, ps, conn);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);        // 回滚
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        try {
            conn.commit(); // 提交业务
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 缓存
        PostmanShopRelationMemory.getInstance().run();
        CityPostmanMemory.getInstance().run();
        UserInfoMemory.getInstance().modifyUserInfo(userInfo.getUsername());
        //===============================================

        return AjaxResult.successResult();
    }


    // 【新】删除配送员
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/new/delete")
    @ResponseBody
    public String city_postman_new_delete(@RequestParam("username") String username,
                                          @RequestParam("city") String city,
                                          String operationUserName) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

        // 骑手有未完成订单，请先转单给其他骑手
        Integer i = PostmanOrderMemoryMan.getPostmanIngOrderCount(username);
        if(i > 0){
            return AjaxResult.errorResult("骑手有未完成订单，请先转单给其他骑手");
        }

        String users = username.replace(",", "','");

        StringBuilder sbCity = new StringBuilder();
        sbCity.append("update ").append(PojoTables.CityPostman).append(" set delFlag = 1,updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and city = '")
                .append(city).append("' and username in ('").append(users).append("')");

        try {
            UserDaoSql.getInstance().executeBySql(sbCity.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //在缓存中删除
        CityPostmanMemory.getInstance().run();
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        // 修改用户类型
        User.delRevertUserStr(username);
        return AjaxResult.successResult();
    }

    /**
     * 修改时，获取初始化数据
     *
     * @param username
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/agent/postman/edit/{username}")
    @ResponseBody
    public String city_postman_edit_init(@PathVariable String username) {
        Map<String, Object> map = new HashMap<>();
        List<ShopInfo> shopInfos = null;
        List<CityPostmanVerifyVO> list = null;
        CityPostman postman = CityPostmanMemory.getInstance().loadPostman(username).get(username);
        if (postman == null) {
            return AjaxResult.errorResult("获取不到骑手信息");
        }
        map.put("postman", postman);
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (userInfo == null) {
            return AjaxResult.errorResult("获取不到用户信息");
        }
        map.put("userInfo", userInfo);

        // 获取骑手审核表信息
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("username", username);
        expression.addChild("delFlag", 0);
        query.addCondition(expression);
        query.addOrders("createTime", "desc");
        String sql = DaoUtils.getSql(PojoTables.POSTMAN_VERITY, query);
        try {
            list = (List<CityPostmanVerifyVO>) UserDaoSql.getInstance().list(CityPostmanVerifyVO.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后再试");
        }
        map.put("postmanVerify", list);

        // 获取骑手对应门店关联表信息
        QueryCondition postmanShopRelationQuery = QueryCondition.getInstance();
        Expression postmanShopRelationExpression = Expression.getInstance();
        postmanShopRelationExpression.addChild("postmanUsername", username);
        postmanShopRelationExpression.addChild("delFlag", 0);
        postmanShopRelationQuery.addCondition(postmanShopRelationExpression);
        postmanShopRelationQuery.addOrders("createTime", "desc");
        String postmanShopRelationSql = DaoUtils.getSql(PojoTables.POSTMAN_SHOP_RELATION, postmanShopRelationQuery);
        List<PostmanShopRelation> postmanShopRelations = null;
        try {
            postmanShopRelations = (List<PostmanShopRelation>) UserDaoSql.getInstance().list(PostmanShopRelation.class, postmanShopRelationSql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后再试");
        }
        if(postmanShopRelations.size() == 1){
            // 关联门店
            QueryCondition shopInfoQuery = QueryCondition.getInstance();
            Expression shopInfoExpression = Expression.getInstance();
            shopInfoExpression.addChild("id", postmanShopRelations.get(0).getShopId());
            shopInfoExpression.addChild("delFlag", 0);
            shopInfoQuery.addCondition(shopInfoExpression);
            shopInfoQuery.addOrders("createTime", "desc");
            String shopSql = DaoUtils.getSql(PojoTables.ShopInfo, shopInfoQuery);
            try {
                shopInfos = (List<ShopInfo>) UserDaoSql.getInstance().list(ShopInfo.class, shopSql);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("获取失败，请稍后再试");
            }
        }

        // 获取骑手所属门店
        map.put("shop", shopInfos);

        return AjaxResult.successResult(map);
    }


    /**
     * 设置关联表属性
     *
     * @param shopInfo
     * @param postman
     * @param createUser
     * @return
     */
    private PostmanShopRelation setPostmanShopRelation(ShopInfo shopInfo, CityPostman postman, String createUser) {
        PostmanShopRelation p = new PostmanShopRelation();
        p.setDelFlag(0);
        p.setPostmanId(postman.getId());
        p.setPostmanUsername(postman.getUsername());
        p.setShopId(shopInfo.getId());
        p.setShopUsername(shopInfo.getOwnUsername());
        p.setCreateUser(createUser);
        p.setCreateTime(DateUtils.getCurrTime());
        return p;
    }

}
